package com.leilei;

import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

import java.util.Arrays;

/**
 * @author lei
 * @version 1.0
 * @date 2021/3/9 22:00
 */
public class OperatorDemo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setRuntimeMode(RuntimeExecutionMode.STREAMING);
        env.setParallelism(1);
        DataStreamSource<String> streamSource = env.socketTextStream("xxx", 8080);
        SingleOutputStreamOperator<Tuple2<String, Integer>> result = streamSource.
                flatMap((FlatMapFunction<String, String>) (s, collector) -> Arrays.stream(s.split(",")).forEach(collector::collect))
                .returns(Types.STRING)
                .filter(s -> !s.equals("sb"))
                .map(String::toUpperCase).returns(Types.STRING)
                .map(s -> Tuple2.of(s, 1)).returns(Types.TUPLE(Types.STRING, Types.INT))
                .keyBy(tp -> tp.f0)
                .reduce((t2, t1) -> Tuple2.of(t1.f0, t1.f1 + t2.f1))
                .returns(Types.TUPLE(Types.STRING,Types.INT));
        result.print();
        env.execute();

    }
}
